package com.meteor.backController;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.meteor.common.R;
import com.meteor.pojo.User;
import com.meteor.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
public class BackUserController {

    @Resource
    private UserService userService;

    /**
     * 访问/user路径进入到登录页面
     */
    @GetMapping
    public String login() {
        return "admin/login";
    }

    /**
     * 判断用户登录是否正确
     */
    @PostMapping("/login")
    public String toLogin(String username, String password, RedirectAttributes attributes, HttpSession session) {
        // 1.将提交的密码进行md5加密
        String pwd = DigestUtils.md5DigestAsHex(password.getBytes());
        // 2.添加条件构造器
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        // 3.添加查询条件
        wrapper.eq("username", username);
        User user = userService.getOne(wrapper);
        if(user == null) {
            attributes.addFlashAttribute("message","用户名和密码错误");
            return "redirect:user/login";
        }
        if(pwd.equals(user.getPassword())) {
            session.setAttribute("user",user);
            return "admin/logIndex";
        }
        attributes.addFlashAttribute("message","用户名和密码错误");
        return "redirect:user/login";
    }

    /**
     * 用户退出
     */
    @GetMapping("/logout")
    public String toLogout(HttpSession session) {
        session.removeAttribute("user");
        return "admin/login";
    }
}
